package com.pn.warehouse.service.impl;

import com.pn.warehouse.entity.InStore;
import com.pn.warehouse.entity.Purchase;
import com.pn.warehouse.entity.Result;
import com.pn.warehouse.mapper.InStoreMapper;
import com.pn.warehouse.mapper.PurchaseMapper;
import com.pn.warehouse.page.Page;
import com.pn.warehouse.service.PurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Resource
    private PurchaseMapper purchaseMapper;

    @Resource
    private InStoreMapper inStoreMapper;

    //添加采购单
    @Override
    public Result insertPurchase(Purchase purchase) {
        //1、添加采购单
        int i = purchaseMapper.insertPurchase(purchase);
        if (i > 0){
            return Result.ok("添加采购单成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "添加采购单失败！");
    }

    //分页查询采购单信息
    @Override
    public Page queryPurchasePage(Page page, Purchase purchase) {
        //1、查询采购单行数
        Integer count = purchaseMapper.findPurchaseCount(purchase);

        //2、分页查询采购单信息
        List<Purchase> purchaseList = purchaseMapper.findPurchasePage(page, purchase);

        //3、封装给page对象，并返回
        page.setTotalNum(count);
        page.setResultList(purchaseList);
        return page;
    }

    //根据id删除采购单
    @Override
    public Result removePurchaseById(Integer purchaseId) {
        int i = purchaseMapper.removePurchaseById(purchaseId);
        if (i > 0){
            return Result.ok("删除采购单成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "删除采购单失败！");
    }

    //根据id修改采购单采购数量和实际采购数量
    @Override
    public Result setNumById(Purchase purchase) {
        int i = purchaseMapper.setNumById(purchase);
        if (i > 0){
            return Result.ok("修改采购单成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "修改采购单失败！");
    }

    //添加入库单
    @Transactional
    @Override
    public Result insertInStore(InStore inStore, Integer buyId) {
        //1、入库
        int j = inStoreMapper.insertInStore(inStore);

        //2、设置采购单状态为已入库
        int i = purchaseMapper.setIsInById(buyId);

        //3、响应结果
        if (i > 0 && j > 0){
            return Result.ok("生成入库单成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "生成入库单失败！");
    }

}
